package com.qiche.controller.mgr;

import com.github.pagehelper.PageInfo;
import com.qiche.aspect.Result;
import com.qiche.dto.StoreMemberDto;
import com.qiche.enums.ResultEnum;
import com.qiche.excel.StoreMemberExcelObj;
import com.qiche.model.InsurancePolicy;
import com.qiche.model.StoreMember;
import com.qiche.model.StoreMemberCar;
import com.qiche.param.StoreMemberParam;
import com.qiche.service.InsurancePolicyService;
import com.qiche.service.StoreMemberCarService;
import com.qiche.service.StoreMemberService;
import com.qiche.util.EasyExcelUtil;
import com.qiche.util.FastDFSUtils;
import com.qiche.util.UserUtils;
import com.qiche.vo.StoreMemberVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 门店客户管理控制器
 * Created by Linzw on 2018/01/24.
 */
@Api(value = "/storeMember",description = "门店客户管理控制器")
@RestController
@RequestMapping("/storeMember")
public class StoreMemberController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private InsurancePolicyService insurancePolicyService;
    @Autowired
    private StoreMemberService storeMemberService;
    @Autowired
    private StoreMemberCarService storeMemberCarService;

    @ApiOperation(value = "根据条件和分页获取门店客户列表")
    @GetMapping
    public Map<String, Object> getAll(StoreMemberParam param,
                                      @RequestParam(required = false, defaultValue = "1") int page,
                                      @RequestParam(required = false, defaultValue = "10") int limit) {
        Map<String, Object> map = new HashMap<>();
        PageInfo<StoreMemberVo> pageInfo = storeMemberService.selectStoreMemberWithCarsByPage(param,page,limit);
        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("count", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        return map;
    }

    @ApiOperation(value = "保存门店客户")
    @PostMapping
    public Result<StoreMemberVo> add(@RequestBody StoreMemberDto storeMemberDto) {
        return storeMemberService.saveStoreMember(storeMemberDto);
    }


    @ApiOperation(value = "根据ID删除门店客户信息")
    @DeleteMapping(value = "/{id}")
    public Result delete(@PathVariable("id") Long id) {
        return storeMemberService.delStoreMember(id);
    }



    @ApiOperation(value = "根据ID获取门店客户信息,并附带属于该会员的车辆信息和保单信息")
    @GetMapping(value = "/{id}")
    public Result get(@PathVariable("id") Long id) {
        StoreMember storeMember= storeMemberService.selectByKey(id);
        List<StoreMemberCar> storeMemberCarList=storeMemberCarService.getCarsByStoreMemberId(storeMember.getId());
        List<InsurancePolicy> policyList=insurancePolicyService.selectByCustomerId(id);
        StoreMemberVo storeMemberVo=new StoreMemberVo();
        storeMemberVo.setId(storeMember.getId());
        storeMemberVo.setName(storeMember.getName());
        storeMemberVo.setPhone(storeMember.getPhone());
        storeMemberVo.setStoreMemberCars(storeMemberCarList);
        storeMemberVo.setStoreMemberPolicys(policyList);
        return  Result.createBySuccess(storeMemberVo);
    }



    @ApiOperation(value = "导入门店客户上传并解析")
    @PostMapping("/upload")
    public Result uploadMembers(MultipartFile file) throws Exception {
        List<StoreMemberExcelObj> list = EasyExcelUtil.importExcel(file, 1, 1, StoreMemberExcelObj.class);
        System.out.println(list.size());
        Integer merchantId = UserUtils.getCurrentUser().getMerchantId();
        if(merchantId == null){
            return Result.createByErrorMessage("不支持的操作");
        }
        if (list != null && !list.isEmpty()) {
            list.forEach(storeMemberExcelObj -> {
                StoreMember storeMember=new StoreMember();
                storeMember.setMerchantId(merchantId.longValue());
                storeMember.setType(storeMemberExcelObj.getType());
                storeMember.setName(storeMemberExcelObj.getName());
                storeMember.setPhone(storeMemberExcelObj.getPhone());
                storeMember.setConsumeMoney(BigDecimal.ZERO);
                storeMemberService.save(storeMember);

                StoreMemberCar storeMemberCar=new StoreMemberCar();
                storeMemberCar.setPlateNumber(storeMemberExcelObj.getPlateNumber());
                storeMemberCar.setCarInfo(storeMemberExcelObj.getCarInfo());
                storeMemberCar.setFrameNumber(storeMemberExcelObj.getFrameNumber());
                storeMemberCar.setStoreMemberId(storeMember.getId());
                storeMemberCarService.save(storeMemberCar);
            });
            return Result.createBySuccessMessage("一共导入了" + list.size() + "条数据");
        }
        return Result.createByErrorMessage("未导入任何数据");
    }


    @ApiOperation(value = "导入门店客户下载模板")
    @GetMapping(value = "/template/down")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        List<StoreMemberExcelObj> list = new ArrayList<>();
        StoreMemberExcelObj obj1 = new StoreMemberExcelObj(2, "张三", "13800******", "粤J*****","本田思域220T","4535345435");
        StoreMemberExcelObj obj2 = new StoreMemberExcelObj(1, "李四", "15088******", "琼B*****","五菱之光","356475765765765");
        list.add(obj1);
        list.add(obj2);
        EasyExcelUtil.exportExcel(list, "需导入的客户列表 客户类型对应关系:(1:普通客户 2:VIP客户)", "sheet1", StoreMemberExcelObj.class, "客户导入模板.xls", response);
    }


    @ApiOperation(value = "根据当前登录门店获取所有门店客户")
    @GetMapping(value = "/getAllStoreMembers")
    public Result getAllStoreMembers() {
       List<StoreMember> storeMemberList= storeMemberService.selectByMerchantId();
       return Result.createBySuccess(storeMemberList);
    }

    @ApiOperation(value = "根据条件获取当前门店客户列表")
    @GetMapping(value = "/getAllStoreMembersByCondition")
    public Result getAllStoreMembersByCondition(Integer type,String phone) {
        Example example =new Example(StoreMember.class);
        Example.Criteria criteria=example.createCriteria();
        if(type!=null){
            criteria.andEqualTo("type",type);
        }
        if(StringUtils.isNotBlank(phone)){
            criteria.andLike("phone","%"+phone+"%");
        }
        criteria.andEqualTo("merchantId", UserUtils.getCurrentUser().getMerchantId());
        List<StoreMember> storeMemberList= storeMemberService.selectByExample(example);
        return Result.createBySuccess(storeMemberList);
    }

    @RequestMapping(value = "/changeType")
    public Result changeType(Long id, Integer status) {
        StoreMember storeMember=storeMemberService.selectByKey(id);

        int isUpdate = 0;
        if (storeMember == null) {
            return Result.createByResultEnum(ResultEnum.FAILURE);
        } else {
            storeMember.setType(status==1?2:1);
            isUpdate = storeMemberService.updateNotNull(storeMember);
            if (isUpdate > 0) {
                return Result.createByResultEnum(ResultEnum.SUCCESS);
            } else {
                return Result.createByResultEnum(ResultEnum.FAILURE);
            }
        }
    }
}




